<?php

namespace app\admin\controller\speech;

use app\common\controller\Backend;
use think\Db;
use think\Env;
use think\Exception;
use think\Config;
use think\Request;
/**
 * 话术管理
 *
 * @icon fa fa-circle-o
 */
class Speech extends Backend
{

    /**
     * Speech模型对象
     * @var \app\admin\model\Speech
     */
    protected $model = null;
    protected $dataLimit = 'auth';



    public function _initialize()
    {
        parent::_initialize();
//        $this->json_all_speech();
        $this->model = model('Speech');
        $this->view->assign("industryList", $this->model->getIndustryList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function copy($id)
    {
        $speech = Db::name('speech')->where('id', $id)->find();
        $speech['name'] = $speech['name'] . '副本';
        $speech['admin_id'] = $this->auth->id;
        $speech['createtime'] = time();
        $speech['updatetime'] = time();
        $speech_id = Db::name('speech')->insertGetId(array_slice($speech, 1));

        $faqs = Db::name('speech_faq')->where('speech_id', $speech['id'])->select();
        foreach ($faqs as $faq) {
            $sound = Db::name('sound')->where('id', $faq['sound_id'])->find();
            $sound['admin_id'] = $this->auth->id;
            $sound['createtime'] = time();
            $sound['updatetime'] = time();
            $sound_id = Db::name('sound')->insertGetId(array_slice($sound, 1));

            $faq['sound_id'] = $sound_id;
            $faq['speech_id'] = $speech_id;
            $faq['admin_id'] = $this->auth->id;
            $faq['createtime'] = time();
            $faq['updatetime'] = time();
            Db::name('speech_faq')->insert(array_slice($faq,1));
        }

        $routers = Db::name('speech_router')->where('speech_id', $speech['id'])->select();
        foreach ($routers as $router) {
            $sound = Db::name('sound')->where('id', $router['sound_id'])->find();
            $sound['admin_id'] = $this->auth->id;
            $sound['createtime'] = time();
            $sound['updatetime'] = time();
            $sound_id = Db::name('sound')->insertGetId(array_slice($sound, 1));

            $no_sound = Db::name('sound')->where('id', $router['no_sound_id'])->find();
            $no_sound['admin_id'] = $this->auth->id;
            $no_sound['createtime'] = time();
            $no_sound['updatetime'] = time();
            $no_sound_id = Db::name('sound')->insertGetId(array_slice($no_sound, 1));

            $router['sound_id'] = $sound_id;
            $router['no_sound_id'] = $no_sound_id;
            $router['speech_id'] = $speech_id;
            $router['admin_id'] = $this->auth->id;
//            $router['createtime'] = time();
//            $router['updatetime'] = time();
            Db::name('speech_router')->insert(array_slice($router,1));
        }

        $router=new Router();
//        $router->json_speech1($speech_id);
        $router->asyn_json(Request::instance()->domain(),$this->request->get('speech_id'));

    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
//                if(Db::name("task")->where())
//                var_dump($v['id']);
                $count += $v->delete();
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['admin_id'] = $this->auth->id;
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public
    function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {

                $row->getRelation('admin')->visible(['id', 'nickname']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function detail($ids)
    {
        return $this->fetch('detail');
    }

}
